🍦 unctx
Composition-api in Vanilla js

What is it?
Vue.js introduced an amazing pattern called Composition API that allows organizing complex logic by splitting it into reusable functions and grouping in logical order. unctx
allows easily implementing composition api pattern in your javascript libraries without hassle.
Integration
In your awesome library:
yarn add unctx
npm install unctx
import { createContext } from 'unctx'
const ctx = createContext()
export const useAwesome = ctx.use
ctx.call({ test: 1 }, () => {
})
User code:
import { useAwesome } from 'awesome-lib'
function setup() {
const ctx = useAwesome()
}
Using Namespaces
To avoid issues with multiple version of library, unctx
provides a safe global namespace to access context by key (kept in globalThis
). Important: Please use a verbose name for key to avoid conflict with other js libraries. Using npm package name is recommended. Using symbols has no effect since it still causes multiple context issue.
import { useContext, getContext } from 'unctx'
const useAwesome = useContext('awesome-lib')
You can also create your own internal namespace with createNamespace
utility for more advanced use cases.
Singleton Pattern
If you are sure it is safe to use a shared instance (not depending to request), you can also use ctx.set
and ctx.unset
for a singleton pattern.
Note: You cannot combine set
with call
. Always use unset
before replacing instance otherwise you will get Context conflict
error.
import { createContext } from 'unctx'
const ctx = createContext()
ctx.set(new Awesome())
export const useAwesome = ctx.use
Typescript
A generic type exists on all utilities to be set for instance/context type:
const { use: useAwesome } = createContext<Awesome>()
Async Context
Normally, using context is only possible before first await statement:
async function setup() {
console.log(useAwesome())
await new Promise(resolve => setTimeout(resolve, 1000))
console.log(useAwesome())
}
A simple workaround, is caching context before first await and use it directly:
async function setup() {
const ctx = useAwesome()
await new Promise(resolve => setTimeout(resolve, 1000))
console.log(ctx)
}
However, this is not always as easy as making a variable when using nested composables.
Unctx provides a better solution that transforms async to automatically restore context after each await call. This requires using a bundler such as Rollup, Vite or Webpack.
Import and register transform plugin:
import { unctxPlugin } from 'unctx/plugin'
unctxPlugin.rollup()
unctxPlugin.vite()
unctxPlugin.webpack()
Use ctx.callAsync
instead of ctx.call
:
await ctx.callAsync('test', setup)
Any async function that requires context, should be wrapped with withAsyncContext
:
import { withAsyncContext } from 'unctx'
const setup = withAsyncContext(async () => {
console.log(useAwesome())
await new Promise(resolve => setTimeout(resolve, 1000))
console.log(useAwesome())
})
Under the hood
Composition of functions is possible using temporary context injection. When calling ctx.call(instance, cb)
, instance
argument will be stored in a temporary variable then cb
is called. Any function inside cb
, can then implicitly access instance by using ctx.use
(or useAwesome
)
Pitfalls
context can be only used before first await:
Please check Async context section.
Context conflict
error:
In your library, you should only keep one call()
running at a time (unless calling with same reference for first argument)
For instance this makes an error:
ctx.call({ test: 1 }, () => {
ctx.call({ test: 2 }, () => {
})
})
License
MIT. Made with 💖